package com.cookbook.animals;

import android.app.Activity;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import android.database.sqlite.*;

import java.util.*;


public class Pair extends Activity{
	// Declare variable to hold db_helper
	DatabaseHelper db_helper;
	
	// Declare variable to hold db
	SQLiteDatabase db;
	
	// Declare variable to hold SQLite statement
	SQLiteStatement statement;
	
	// Declare variable to hold id of current animal
	int id;
	
	// Declare variable to hold number of questions answered
	int answered;
	
	// Declare array to hold ids of animals chosen
	int animals[] = new int[10];
	
	// Declare variable to hold name of user
	String user;
	
	// Declare ArrayList<String> variable to hold names of animals
	ArrayList<String> names = new ArrayList<String>();
	
	// Declare TextView to display animals name
	TextView name;
	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pair_picture);

        // Instantiate new DatabaseHelper variable
        db_helper = new DatabaseHelper(this);
        
        // Check if savedInstanceState is non-null
        if(savedInstanceState != null){
        	// If so get info of last state
        	
        	// Get user from bundle
        	user = savedInstanceState.getString("user");
        	
        	// Get id from bundle
        	id = savedInstanceState.getInt("id");
        	
        	// Get animals array from bundle
        	animals = savedInstanceState.getIntArray("animals");
        	
        	// Get answered from bundle
        	answered = savedInstanceState.getInt("answered");
        }
        
        // Else there was no last state so generate new info
        else{
        	// Get user from calling activity
        	user = this.getIntent().getStringExtra("user");
            
        	// Generate 10 random animals from database and save id's to array
            animals = generateAnimals();
            
            // Initialize answered variable to 0
            answered = 0;

            // Initialize id to id of first animal
            id = animals[answered];
        }
        
        // Instantiate correct button
        Button correct = (Button) findViewById(R.id.correct);
        
        // Instantiate incorrect button
        Button incorrect = (Button) findViewById(R.id.incorrect);
        
        // Instantiate RelativeLayout
        RelativeLayout background = (RelativeLayout) findViewById(R.id.relativeLayout1);
        
		// Instantiate picture id to 0
		int picture_id = 0;
		
		// Check if current orientation is portrait
		if(this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
			// If so convert id of animal to id of its portrait picture
			picture_id = id2Picture1(id);
		}
		
		// Else current orientation is landscape
		else{
			// If so convert id of animal to id of its landscape picture
			picture_id = id2Picture2(id);
		}
        
        // Load picture into background of layout
        background.setBackgroundResource(picture_id);
      
        // Fill names array with a buffer spot and all of the animals names
        names.add("buffer");
        names.add("Cow");
        names.add("Pig");
        names.add("Dog");
        names.add("Horse");
        names.add("Sheep");
        names.add("Cat");
        names.add("Chicken");
        names.add("Squirrel");
        names.add("Duck");
        names.add("Frog");
        names.add("Turkey");
        names.add("Lion");
        names.add("Tiger");
        names.add("Bear");
        names.add("Monkey");
        names.add("Fish");
        names.add("Parrot");
        names.add("Dolphin");
        names.add("Eagle");
        names.add("Donkey");
        names.add("Wolf");
        names.add("Snake");
        names.add("Mouse");
        names.add("Elephant");
        names.add("Bee");
        names.add("Bat");
        names.add("Cricket");
        names.add("Goose");
        names.add("Rooster");
        names.add("Owl");
    
        // Instantiate name TextView
        name = (TextView) findViewById(R.id.pair_name);
        
        // Start a listener for incorrect button
        incorrect.setOnClickListener(new View.OnClickListener() {
			// Override onClick function
			@Override
			public void onClick(View v){
				// Open database for reading and writing
				db = db_helper.getWritableDatabase();
				
				// Read frequency for this animal from database
				Long frequency = db_helper.getFrequency(db, user, id);
				
				// Read stats from database
				ArrayList<Long> stats = db_helper.getStats(db, user);
				
				// Increase frequency for this animal in the database
				db_helper.updateFrequency(db, user, id, frequency.intValue() + 1);
				
				// Update total field in stats table
				db_helper.updateTotal(db, user, stats.get(1).intValue() + 1);
			
				// Increase answered
				answered++;
				
				// Close database
				db.close();
				
				// Check if answered is 10
				if(answered == 10){
					// If so then close this activity
					finish();
				}
				
				// Else continue
				else{
					// Set id to be id of next animal
					id = animals[answered];
				
					// Instantiate picture id to 0
					int picture_id = 0;
					
					// Check if current orientation is portrait
					if(Pair.this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
						// If so convert id of animal to id of its portrait picture
						picture_id = id2Picture1(id);
					}
					
					// Else current orientation is landscape
					else{
						// If so convert id of animal to id of its landscape picture
						picture_id = id2Picture2(id);
					}
		        	
		        	// Instantiate RelativeLayout
		        	RelativeLayout background = (RelativeLayout) findViewById(R.id.relativeLayout1);
		        	
		        	// Load picture into background of layout
		        	background.setBackgroundResource(picture_id);
				}
			}
		});
        
        // Start a listener for correct button
        correct.setOnClickListener(new View.OnClickListener() {
			// Override onClick function
			@Override
			public void onClick(View v) {		
				// Set the text of name to be this animals name
				name.setText(names.get(id));
				
				// Convert id of animal to id of sound
				int sound_id = id2Sound(id);
				
				// Prepare sound of animal
				MediaPlayer mp = MediaPlayer.create(getApplicationContext(), sound_id);
				
				// Make sure mp is non-null
				if(mp != null){
					// Play sound of animal
					mp.start();
				}
				
				// Else mp is null
				else{
					// Give user an error message
					Toast.makeText(getApplicationContext(), "Error: Can't play animals sound", Toast.LENGTH_SHORT).show();
				}
				
				// Open database for reading and writing
				db = db_helper.getWritableDatabase();
				
				// Get this animals color 
				int color = db_helper.getColor(db, id);
				
				// Check if color is 0
				if(color == 0){
					// If so change color to hexcode for black
					color = 0xff000000;
				}
				
				// Else it was white
				else{
					// If so change color to be hexcode for white
					color = 0xffffffff;
				}
				
				// Change text color of name
				name.setTextColor(color);
				
				// Make name visible
				name.setVisibility(0);
				
				// Read numbers for this animal from database
				Long frequency = db_helper.getFrequency(db, user, id);
				
				// Read stats for from database
				ArrayList<Long> stats = db_helper.getStats(db, user);
				
				// Update total and correct in stats table
				db_helper.updateCorrect(db, user, stats.get(0).intValue() + 1);
				db_helper.updateTotal(db, user, stats.get(1).intValue() + 1);
				
				// Check if frequency is greater than 1
				if(frequency.intValue() > 1){
					// If so then decrease frequency for this animal in the database
					db_helper.updateFrequency(db, user, id, frequency.intValue() - 1);
				}
				
				// Close database
				db.close();
				
				// Increase answered
				answered++;
				
				// Set onCompletionListener for mp2
				mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
					// Override onCompletion function
					@Override
					public void onCompletion(MediaPlayer mp){
	    				// Release mp2
	    				mp.release();
	    				
	    				// Check if answered is 10
	    				if(answered == 10){
	    					// If so then close this activity
	    					finish();
	    				}
	    				
	    				// Else continue
	    				else{
	    					// Make name invisible
	    					name.setVisibility(4);
	    					
	    					// Set id to be id of next animal
	    					id = animals[answered];
	    					
	    					// Instantiate picture id to 0
	    					int picture_id = 0;
	    					
	    					// Check if current orientation is portrait
	    					if(Pair.this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
	    						// If so convert id of animal to id of its portrait picture
	    						picture_id = id2Picture1(id);
	    					}
	    					
	    					// Else current orientation is landscape
	    					else{
	    						// If so convert id of animal to id of its landscape picture
	    						picture_id = id2Picture2(id);
	    					}
	    		        	
	    		        	// Instantiate RelativeLayout
	    		        	RelativeLayout background = (RelativeLayout) findViewById(R.id.relativeLayout1);
	    		        	
	    		        	// Load picture of animal into background of layout
	    		        	background.setBackgroundResource(picture_id);
	    				}
	    			}
				});
			}
		});
    }	    
    
    // Override onSavedInstanceState function
    @Override
    public void onSaveInstanceState(Bundle outState){
    	// Call super function
    	super.onSaveInstanceState(outState);
    	
    	// Put user into outState bundle
    	outState.putString("user", user);
    	
    	// Put id into outState bundle
    	outState.putInt("id", id);
    	
    	// Put animals array into outState bundle
    	outState.putIntArray("animals", animals);
    	
    	// Put answered into outState bundle
    	outState.putInt("answered", answered);
    }
    
    // Define generateAnimals function
    private int[] generateAnimals(){
    	// Create Long to hold results of database querries
    	Long results;
    	
    	// Create array to hold frequency of every animal in the database
    	ArrayList<Long> frequencies = new ArrayList<Long>();
    	
    	// Create array to hold id's of animals chosen and initialize values to -1
    	int ids[] = new int[10];
    	for(int i = 0; i < 10; i++){
    		ids[i] = -1;
    	}
    	
    	// Create variable to hold sum of all frequencies
    	int sum = 0;
    	
    	// Open database for reading and writing
    	db = db_helper.getWritableDatabase();
    	
    	// Fill frequencies with a query of database for every animal entry and sum them all
    	for(int i = 1; i <= DatabaseHelper.DB_SIZE; i++){
    		results = db_helper.getFrequency(db, user, i);
    		frequencies.add(results);
    		sum += results.intValue();
    	}
    	
    	// Close database
    	db.close();
    	
    	// Prepare a second array to hold id's of animals in database
    		// each animal gets as many spots as its frequency
    	if(sum > 0){
    		int chances[] = new int[sum];
    		int counter = 0;
    		for(int i = 0; i < DatabaseHelper.DB_SIZE; i++){
    			// Get frequency of current animal
    			int frequency = frequencies.get(i).intValue();
    		
    			// Add as many entries into chance array is animal has frequency
    			for(int j = 0; j < frequency; j++){
    				chances[counter++] = i+1;
    			}
    		}
    	
    		// Instantiate random number generator
    		Random randomGenerator = new Random();
    	
    		// Repeat selection method 10 times to pick 10 animals
    		for(int i = 0; i < 10; i++){
    			// Generate a random number between 0 and sum-1
    			int random_num = randomGenerator.nextInt(sum);
    		
    			// Get the id held in that entry in chances array
    			int choice = chances[random_num];
    		
    			// Make sure choice isn't already in animals
    			for(int j = 0; j < 10; j++){
    				if(choice == ids[j]){
    					// If it is a repeat then set choice to -1 and break for loop 
    					choice = -1;
    					break;
    				}
    			}
    		
    			// Check if choice is -1
    			if(choice == -1){
    				// If so random id chosen was a repeat so decrement i and repeat this
    					// iteration of selection method
    				i--;
    			}
    		
    			// Else assign id value in choice to current position in animals
    			else{
    				ids[i] = choice;
    			}
    		}
    	}
    	// Return animals
    	return ids;
    }
    
    // Make function to convert an animals id in the database to the id of its portrait picture
    int id2Picture1(int id){
    	return id + 0x7f020000 - 1;
    }
    
    // Make function to convert an animals id in the database to the id of its landscape picture
    int id2Picture2(int id){
    	return id + 0x7f020000 - 1 + DatabaseHelper.DB_SIZE;
    }
    
    // Make function to convert an animals id in the database to the id of its sound
    int id2Sound(int id){
    	return id + 0x7f040000 - 1;
    }
}
